package com.itheima.servlet;

import com.itheima.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/listStudentServlet")
public class ListStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     //创建字符输入流   读取文件
        BufferedReader br = new BufferedReader(new FileReader("d:\\stu.txt"));
        ArrayList<Student> list = new ArrayList<>();
//        循环读取文件数据 封装到Student中 再存入集合
        String line;
        while ((line = br.readLine()) != null) {
            Student stu = new Student();
            String[] split = line.split(",");
            stu.setUsername(split[0]);
            stu.setAge(Integer.parseInt(split[1]));
            stu.setScore(Integer.parseInt(split[2]));
            list.add(stu);
        }
        //集合存入会话域中
        req.getSession().setAttribute("students", list);
//        重定向到学生列表页面
        resp.sendRedirect("/stu1/listStudent.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
